package com.shujia.mysql;

import java.sql.*;

/**
 * @Description: MysqlJdbc1  使用PreparedStatement
 * @Author: 王火火
 * @Date: 2019/9/6 10:38
 */
public class MysqlJdbc1 {
    //创建常量
    static final String DRIVER = "com.mysql.jdbc.Driver";//驱动
    static final String URL = "jdbc:mysql://master:3306/shujia";//路劲
    static final String USERNAME = "root";//用户名
    static final String PASSWORD = "123456";//密码

    public static void main(String[] args) throws Exception {
        //1.加载驱动
        Class.forName(DRIVER);
        //2.获取连接
        Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        String sql = "select * from emp where ename=?";
        //3.获取执行器  把sql语句放到执行器中进行编译
        PreparedStatement ps = conn.prepareStatement(sql);
        //sql语句中的？需要通过ps来给参数
        /**
         * @Description: sql中的参数 不是通过拼接的 是通过下标获取位置类进行的参数传递
         * @param: [args]
         * @return: void
         * @auther: 王火火
         * @date: 2019/9/6 11:17
         *
         * 想要sql注入的结果 select * from emp where ename="'SMITH' or 1=1";
         */
        ps.setString(1, "SMITH");


        //4.执行获取结果
        ResultSet rs = ps.executeQuery();
        //5.循环输出结果(展开结果集)
        while (rs.next()) {
            //获取mysql中具体的值
            int empno = rs.getInt("EMPNO");
            String ename = rs.getString("ENAME");
            String job = rs.getString("JOB");
            String mgr = rs.getString("MGR");
            Date hiredate = rs.getDate("HIREDATE");
            int sal = rs.getInt("SAL");
            int comm = rs.getInt("COMM");
            int deptno = rs.getInt("DEPTNO");
            System.out.println(empno + "--" + ename + "--" + job + "--"
                    + mgr + "--"
                    + hiredate + "--"
                    + sal + "--"
                    + comm + "--"
                    + deptno);
        }
        //6.关闭
        rs.close();
        ps.close();
        conn.close();
    }
}
